package com.example.bookexchange;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Button;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.app.AlertDialog;  // 导入 AlertDialog
import androidx.appcompat.app.AppCompatActivity;

public class OrderDetailsActivity extends AppCompatActivity {

    private TextView tvSelectAddress, tvPickupTime, tvTotalBooks, tvEstimatedPrice;
    private LinearLayout bookInfoContainer; // 用于存放书籍信息的容器
    private String selectedDay, selectedTime; // 用于存储选择的日期和时间
    private AlertDialog alertDialog; // 对话框对象
    private int selectedDayPosition = -1; // 用于标记选中的日期
    private int selectedTimePosition = -1; // 用于标记选中的时间
    private String[] bookNames;
    private double[] bookPrices;
    private int[] bookQuantities;
    private int[] bookImages;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_details);

        tvSelectAddress = findViewById(R.id.tvSelectAddress);
        tvPickupTime = findViewById(R.id.tvPickupTime);
        tvTotalBooks = findViewById(R.id.tvTotalBooks); // 获取总数显示的 TextView
        tvEstimatedPrice = findViewById(R.id.tvEstimatedPrice); // 获取回收价显示的 TextView
        bookInfoContainer = findViewById(R.id.bookInfoContainer); // 获取书籍信息容器

        // 收货地址选择
        tvSelectAddress.setOnClickListener(v -> {
            Intent intent = new Intent(OrderDetailsActivity.this, AddressActivity.class);
            startActivityForResult(intent, 1); // 请求码 1 用于接收地址
        });

        // 弹出时间选择对话框
        tvPickupTime.setOnClickListener(v -> showPickupTimeDialog());

        // 提交订单按钮
        findViewById(R.id.btnSubmitOrder).setOnClickListener(v -> {
            Intent intent = new Intent(OrderDetailsActivity.this, OrderSuccessActivity.class);
            startActivity(intent);
        });

        // 从 Intent 获取传递过来的书籍信息
        Intent intent = getIntent();
        bookNames = intent.getStringArrayExtra("bookNames");
        bookPrices = intent.getDoubleArrayExtra("bookPrices");
        bookQuantities = intent.getIntArrayExtra("bookQuantities");
        bookImages = intent.getIntArrayExtra("bookImages"); // 获取传递的书籍图片

        // 显示书籍信息
        displayBookInfo();
    }

    // 显示书籍信息
    private void displayBookInfo() {
        LayoutInflater inflater = getLayoutInflater();
        double totalPrice = 0;
        int totalBooks = 0; // 统计书籍总数

        // 遍历书籍并显示
        for (int i = 0; i < bookNames.length; i++) {
            // 如果数量为0，则跳过该书籍
            if (bookQuantities[i] == 0) {
                continue; // 跳过当前循环，进入下一本书
            }

            // 创建书籍信息的视图
            View bookView = inflater.inflate(R.layout.book_item, null);

            // 获取视图中的控件
            TextView tvBookName = bookView.findViewById(R.id.tvBookName);
            TextView tvBookPrice = bookView.findViewById(R.id.tvBookPrice);
            TextView tvBookQuantity = bookView.findViewById(R.id.tvBookQuantity); // 新增数量显示的控件
            ImageView ivBookImage = bookView.findViewById(R.id.ivBookImage); // 书籍图片

            // 设置书籍信息
            tvBookName.setText(bookNames[i]);
            tvBookPrice.setText("￥" + bookPrices[i]);  // 显示回收价
            tvBookQuantity.setText("" + bookQuantities[i]);  // 显示数量
            ivBookImage.setImageResource(bookImages[i]); // 设置对应书籍的图片

            // 将书籍信息视图添加到容器中
            bookInfoContainer.addView(bookView);

            // 更新总价格和总书籍数量
            totalPrice += bookPrices[i] * bookQuantities[i];
            totalBooks += bookQuantities[i];
        }

        // 更新总价和总书籍数量
        tvTotalBooks.setText("" + totalBooks);
        tvEstimatedPrice.setText("￥" + totalPrice);
    }

    // 弹出时间选择对话框
    private void showPickupTimeDialog() {
        String[] days = {"星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"};
        String[] times = {"10:00 ~ 11:00", "11:00 ~ 12:00", "12:00 ~ 13:00", "13:00 ~ 14:00",
                "14:00 ~ 15:00", "15:00 ~ 16:00", "16:00 ~ 17:00", "17:00 ~ 18:00"};

        // 创建一个自定义布局
        View dialogView = getLayoutInflater().inflate(R.layout.pickup_time_dialog, null);

        // 获取自定义布局中的 GridView
        GridView gridViewDays = dialogView.findViewById(R.id.gridViewDays);
        GridView gridViewTimes = dialogView.findViewById(R.id.gridViewTimes);
        Button btnConfirm = dialogView.findViewById(R.id.btnConfirm);

        // 设置星期和时间的适配器
        gridViewDays.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, days));
        gridViewTimes.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, times));

        // 设置点击事件，选择星期和时间
        gridViewDays.setOnItemClickListener((parent, view, position, id) -> {
            selectedDay = days[position];
            selectedDayPosition = position; // 保存选择的星期位置
            updateItemBackground(gridViewDays, position); // 更新背景颜色
            Toast.makeText(OrderDetailsActivity.this, "选择了: " + selectedDay, Toast.LENGTH_SHORT).show();
        });

        gridViewTimes.setOnItemClickListener((parent, view, position, id) -> {
            selectedTime = times[position];
            selectedTimePosition = position; // 保存选择的时间位置
            updateItemBackground(gridViewTimes, position); // 更新背景颜色
            Toast.makeText(OrderDetailsActivity.this, "选择了: " + selectedTime, Toast.LENGTH_SHORT).show();
        });

        // 确定按钮
        btnConfirm.setOnClickListener(v -> {
            // 这里根据选择的星期和时间来更新 tvPickupTime
            if (selectedDay != null && selectedTime != null) {
                tvPickupTime.setText(selectedDay + " " + selectedTime);
            } else {
                Toast.makeText(OrderDetailsActivity.this, "请选择时间", Toast.LENGTH_SHORT).show();
            }
            alertDialog.dismiss(); // 关闭对话框
        });

        // 创建并显示对话框
        alertDialog = new AlertDialog.Builder(this)
                .setView(dialogView)
                .setCancelable(true)
                .show();  // 显示对话框
    }

    // 被选中项的背景颜色
    private void updateItemBackground(GridView gridView, int selectedPosition) {
        for (int i = 0; i < gridView.getChildCount(); i++) {
            View item = gridView.getChildAt(i);
            if (i == selectedPosition) {
                item.setBackgroundResource(R.drawable.item_background_selected); // 选中时的背景
            } else {
                item.setBackgroundResource(R.drawable.item_background_default); // 默认背景
            }
        }
    }

    // 获取地址的返回值
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            // 获取从 AddressActivity 返回的选择的地址
            String selectedAddress = data.getStringExtra("selectedAddress");
            tvSelectAddress.setText(selectedAddress); // 设置选择的地址
        }
    }
}
